package com.hup.vd.view.customView;

import com.hup.utils.commons.start.AppIcon;
import com.hup.utils.commons.start.LookThemeUtil;
import com.hup.utils.commons.start.SpringContext;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * 限速控件弹窗,滑块的刻度是非线性的
 *
 * @author hugan
 * @date 2022/8/13
 */
@Slf4j
public class RateLimitDialog extends JDialog {
    public JSlider slRateLimit;

    /**
     * slider的刻度对应的实际值,单位K
     */
    public ArrayList<Integer> values;

    @Setter
    private RateChangedListener rateChangedListener;

    public RateLimitDialog() {
        super((Frame) null);
        setIconImage(SpringContext.getBean(AppIcon.class).getImage());
        setUndecorated(true);
        setAlwaysOnTop(true);
        LookThemeUtil.initFrameSize(this, 450, 70);

        $$$setupUI$$$();
        initView();
        initListener();
    }

    private void $$$setupUI$$$() {
        JPanel root = new JPanel(new GridBagLayout());
        root.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
        add(root);
        //
        slRateLimit = new JSlider();
        slRateLimit.setMajorTickSpacing(10);
        slRateLimit.setMinorTickSpacing(1);
        slRateLimit.setPaintLabels(true);
        slRateLimit.setPaintTicks(true);
        slRateLimit.setValue(0);
        GridBagConstraints gbc;
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.anchor = GridBagConstraints.SOUTH;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 10, 10, 10);
        root.add(slRateLimit, gbc);
    }

    private void initView() {
        //构造实际流量值的list
        int[][] valueConfig = {
                //递增值,上限值(包含), 单位K
                {20, 200},
                {50, 500},
                {100, 900},
                {124, 1024},//对齐到1M
                {1024, 20480},
                {1024 * 5, 51200},
        };
        int value = 20;//起始值
        values = new ArrayList<>();
        values.add(0);//不限速
        values.add(value);//起始值
        for (int[] config : valueConfig) {
            int step = config[0];
            int max = config[1];
            while (value < max) values.add(value += step);
        }
        //log.info("values={}, {}", values.size(), values);
        slRateLimit.setMaximum(values.size() - 1);
        //构造刻度label
        Hashtable<Integer, JLabel> labels = new Hashtable<>();
        Font font = getFont().deriveFont(LookThemeUtil.getDefaultScaledFontSize() * 0.8F);
        labels.put(0, new JLabel("不限速", JLabel.CENTER));
        for (int i = slRateLimit.getMajorTickSpacing(); i < slRateLimit.getMaximum(); i += slRateLimit.getMajorTickSpacing()) {
            labels.put(i, new JLabel(FileUtils.byteCountToDisplaySize(values.get(i) * 1024).replace(" ", ""), JLabel.CENTER));
        }
        labels.put(slRateLimit.getMaximum(), new JLabel(FileUtils.byteCountToDisplaySize(values.get(slRateLimit.getMaximum()) * 1024).replace(" ", ""), JLabel.CENTER));
        Enumeration<JLabel> elements = labels.elements();
        while (elements.hasMoreElements()) elements.nextElement().setFont(font);
        slRateLimit.setLabelTable(labels);
    }

    private void initListener() {
        slRateLimit.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                //log.info("");
                dispose();
            }
        });
        slRateLimit.addChangeListener(e -> {
            if (rateChangedListener == null) return;//启动时,初始化slider值会触发回调

            int index = slRateLimit.getValue();
            Integer kb = values.get(index);
            //log.info("{}={}, {}", index, kb, FileUtils.byteCountToDisplaySize(kb * 1024));
            if (index == 0) kb = null;
            rateChangedListener.onChanged(kb, slRateLimit.getValueIsAdjusting());
        });
    }

    public void doShow(JComponent label) {
        Point loc = label.getLocationOnScreen();
        setLocation(loc.x, loc.y + label.getHeight());
        setVisible(true);
        slRateLimit.requestFocus();
    }

    public interface RateChangedListener {
        /**
         * @param kb 限速值,单位kb,nullable,
         * @param isAdjusting true-正在拖拽,false-拖拽结束/放开鼠标
         */
        void onChanged(Integer kb, boolean isAdjusting);
    }

}
